package com.mgface.metadata.design.udd;

import lombok.extern.slf4j.Slf4j;
import org.apache.calcite.config.Lex;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.parser.SqlParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project mddesign
 * @create 2021-06-07 15:54
 **/
@Component
@Slf4j
public class UDDEngine {

    private static final SqlParser.Config config = SqlParser.configBuilder().setLex(Lex.MYSQL).build();
    @Autowired
    private DataSource datasource;
    @Autowired
    private MgfaceSelectParser mgfaceSelectParser;

    //    @Autowired
//    private MgfaceDeleteParser mgfaceDeleteParser;
//    @Autowired
//    private MgfaceInsertParser mgfaceInsertParser;
//    @Autowired
//    private MgfaceUpdateParser mgfaceUpdateParser;
    public String exec(String sql) {

        //sql = "select a.CustomerNo as cno,a.CustomerName as cname,b.OrderNo as ono from Customer a inner join Orders b on a.CustomerNo=b.Customer inner join OrderItem c on b.OrderNo = c.Orders where b.OrderNo = 'ON201903091914A0100001'";

        //sql = "select a.ItemPrice as iprice,b.ProductName as pname from OrderItem a INNER JOIN Product b on a.Product=b.guid";

        sql = "select a.ItemPrice as iprice from OrderItem a";
        try {
            SqlParser sqlParser = SqlParser.create(sql, config);
            SqlNode sqlNode = sqlParser.parseStmt();
            switch (sqlNode.getKind()) {
                case SELECT:
                    return mgfaceSelectParser.exec(datasource, sqlNode, sql);
                //                case UPDATE:
//                    mgfaceUpdateParser.exec(datasource, sqlNode, sql);
//                    break;
//                case INSERT:
//                    mgfaceInsertParser.exec(datasource, sqlNode, sql);
//                    break;
//                case DELETE:
//                    mgfaceDeleteParser.exec(datasource, sqlNode, sql);
//                    break;
                default:
                    throw new RuntimeException("暂不支持CRUD之外的操作.(unsupported operations)");
            }
        } catch (Exception e) {
            log.error("执行SQL操作发生异常.(An exception occurred while executing SQL)");
            throw new RuntimeException(e.getMessage());
        }
    }
}
